package com.example.guideapp.fragment;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.example.guideapp.R;
import com.example.guideapp.activity.ChooseMsgActivity;
import com.example.guideapp.adapter.MyFestivalGridViewAdapter;
import com.example.guideapp.bean.Festival;
import com.example.guideapp.utils.DatabaseManage;
import com.example.guideapp.utils.MySqliteDatabaseHelper;

import java.util.List;

/**
 * Created by Administrator on 2017/10/16.
 */

public class Fragment1 extends Fragment {

    public static final String TYPE = "type";
    public static final String FESTIVAL = "festival";
    public static final String FESTIVALID = "festivalId";
    public static final String FESTIVALNAME = "festivalName";

    private GridView mGridView;
    private LayoutInflater mInFlater;

    private List<Festival> list;

    private MySqliteDatabaseHelper helper;

    private MyFestivalGridViewAdapter adapter;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment1,container,false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        helper = DatabaseManage.getInstance(getActivity());
        mInFlater = LayoutInflater.from(getActivity());

        if (view == null){
            view = mInFlater.inflate(R.layout.fragment1,null);
        }

        mGridView = (GridView) view.findViewById(R.id.fragment1_gridView);

        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from Festival",null);

        list = DatabaseManage.festivalCursorToList(cursor);
        db.close();

        adapter = new MyFestivalGridViewAdapter(getActivity(),list);

        mGridView.setAdapter(adapter);

        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(getActivity(), ChooseMsgActivity.class);
                intent.putExtra(TYPE,FESTIVAL);
                intent.putExtra(FESTIVALID,list.get(position).getId());
                intent.putExtra(FESTIVALNAME,list.get(position).getFestivalName());
                startActivity(intent);
            }
        });
    }
}
